package com.mayblackcat.dy.controller;

import com.mayblackcat.dy.FrontEndData.AjaxResult;
import com.mayblackcat.dy.entity.Comment;
import com.mayblackcat.dy.entity.User;
import com.mayblackcat.dy.service.CommentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/login")
@Api(tags = "用户信息管理")
public class CommentController {

    @Autowired
    private CommentService commentService;


    @Value("${user.avatar}")
    private String avatar;



    //    查询留言
    @ApiOperation("查询评论区")
    @GetMapping("/comment")
    public Model comment(Model model) {
        List<Comment> comments = commentService.listComment();
        model.addAttribute("comments", comments);
        model.addAttribute("code","200");
        model.addAttribute("msg","查询成功");
        return model;
    }

    //    新增留言
    @ApiOperation("新增评论区")
    @ApiImplicitParams({ @ApiImplicitParam(name="comment",value = "评论区",required=true,paramType="path",dataType="Comment") })
    @PostMapping("/addComment")
    public Model addComment(@RequestBody Comment comment, HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        //设置头像
        if (user != null) {
            comment.setAvatar(user.getAvatar());
            comment.setVideoId(user.getId());
        } else {
            comment.setAvatar(avatar);
        }
        if (comment.getParentComment().getId() != null) {
            comment.setParentCommentId(comment.getParentComment().getId());
        }
        commentService.saveComment(comment);
        List<Comment> comments = commentService.listComment();
        model.addAttribute("comments", comments);
        model.addAttribute("code","200");
        model.addAttribute("msg","查询成功");
        return model;
    }

    //    删除留言
    @ApiOperation("删除评论")
    @GetMapping("/comment/{id}/delete")
    public AjaxResult delete(@PathVariable Long id) {
        commentService.deleteComment(id);
        return new AjaxResult(AjaxResult.Type.SUCCESS,"success");
    }
}
